package com.netty.rpc.thread;

import com.netty.rpc.req.CalcRequest;
import com.netty.rpc.resp.CalcResponse;
import com.netty.rpc.resp.Response;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.Callable;

public class WorkerTask implements Callable<Response> {

    private Map<String, Object> servicesMap;

    private ChannelHandlerContext context;

    private CalcRequest request;

    public WorkerTask(ChannelHandlerContext context, CalcRequest request, Map<String, Object> servicesMap){
        this.context = context;
        this.request =  request;
        this.servicesMap = servicesMap;
    }

    @Override
    public Response call() throws Exception {
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.directBuffer();
        byteBuf.writeBytes("netty byte 。。。。".getBytes());
        String serviceName = request.getServiceName();
        String methodName = request.getMethodName();
        Class[] paramsTypes = request.getParamsTypes();
        Object[] params = request.getParams();
        Object service = servicesMap.get(serviceName);
        Method method = service.getClass().getMethod(methodName, paramsTypes);
        Object result = method.invoke(service, params);
        CalcResponse response = new CalcResponse();
        response.setResult(result);
        return response;
    }
}
